package com.example.demo.interceptor;

import com.example.demo.exception.BusinessException;
import com.example.demo.exception.ErrorCode;
import com.example.demo.service.ManagerService;
import com.example.demo.entity.*;
import com.example.demo.utils.JwtUtils;
import com.example.demo.utils.UserContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private ManagerService managerService;
    

    @SuppressWarnings("null")
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的token
        String token = request.getHeader("token");
        
        // 检查token是否存在
        if (token == null) {
            throw new BusinessException(ErrorCode.UNAUTHORIZED, "非法token，请先登录！");
        }

        // 验证token
        if (!jwtUtils.validateToken(token)) {
            throw new BusinessException(ErrorCode.UNAUTHORIZED, "token已过期或无效");
        }
        
        // 检查token是否在黑名单中
        if (jwtUtils.isTokenBlacklisted(token)) {
            throw new BusinessException(ErrorCode.UNAUTHORIZED, "token已被注销");
        }

        // 将用户名存入ThreadLocal
        String username = jwtUtils.getUsernameFromToken(token);

        Manager manager = managerService.getManagerByUsername(username);
        
        UserContext.setUserId(manager.getId().toString());
        UserContext.setManager(manager);
        
        return true;
    }

    @SuppressWarnings("null")
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清除ThreadLocal中的用户信息
        UserContext.clear();
    }
}
